﻿using System;
using System.Linq;

namespace RazakiSite.UserControls
{
    public partial class UCUploadFile : BaseUserControl
    {

        public bool FileIsCorrect { get; set; }

        private string FileKey
        {
            get
            {
                if (ViewState["FileKey"] == null)
                    ViewState["FileKey"] = UtilitiesBLL.GenerateGuid();

                return ViewState["FileKey"].ToString();
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {

            //always run
            if (IsPostBack)
            {
                //after postback
                SetFile();
                return;
            }
            //first time

        }

        private void SetFile()
        {
            if (ValidateControls())
                FileIsCorrect = true;
            else
            {
                FileIsCorrect = false;
                return;
            }

            if (UplFile.UploadedFiles.Count != 1)
                return;

            var uploadedFile = UplFile.UploadedFiles[0];
            var image = new byte[uploadedFile.ContentLength];

            uploadedFile.InputStream.Read(image, 0, uploadedFile.ContentLength);

            UtilitiesUI.SessionSet(FileKey, image);
        }

        private bool ValidateControls()
        {
            //فایلی بارگذاری نشده است
            if (UplFile.UploadedFiles.Count != 1)
                return true;

            var uploadedFile = UplFile.UploadedFiles[0];

            return UplFile.AllowedFileExtensions.Contains(uploadedFile.GetExtension());
        }

        public byte[] GetFile()
        {
            return UtilitiesUI.SessionGet<byte[]>(FileKey);
        }

        public void ClearFile()
        {
            UtilitiesUI.SessionClear(FileKey);
        }

    }
}